﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using weclever.Navigation;
using weclever.Infrastructure;
using HtmlAgilityPack;
using System.IO;
using System.Text.RegularExpressions;

namespace weclever.Pages
{
    public class CityPositionPage
    {
        private City LocationCity { get; set; }
        private string PositionName { get; set; }
        private string siteHtml = "";
        private HtmlNode node = null;
        private HtmlDocument doc = null;


        public string SiteHtml { get { return siteHtml; } }

        private IPageCommunication PageCommunication { get; set; }

        public CityPositionPage(IPageCommunication pageCommunication, City city, string positionName)
        {
            LocationCity = city.Clone() as City;
            PageCommunication = pageCommunication;
            PositionName = positionName;
            siteHtml = PageCommunication.NavigateToURL(SiteUrls.MakeAddress(city.NameEng, positionName));
            doc = new HtmlDocument();
            doc.LoadHtml(siteHtml);
            node = doc.DocumentNode;
            // NumberPropositions();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns>Information from page or null if there is no title</returns>
        public PageInfo ExtractInfo()
        {
            PageInfo pageInfo = new PageInfo();
            pageInfo.Name = PositionName;
            pageInfo.CityName = LocationCity.Clone() as City;
            bool res;
            pageInfo.Title = ExtractText("//div[@class='weclever_action_main']/h1", out res);
            if (!res) { return null;  }//There is no title, maybe exception should be here
            pageInfo.Price = ExtractText("//td[@class='weclever_action_price']", out res);
            pageInfo.Discount = ExtractText("//tr[@class='weclever_action_oldprice_quant']/td", out res);
            pageInfo.Economy = ExtractText("//tr[@class='weclever_action_oldprice_quant']/td/span[@class='na']", out res);
            pageInfo.Bought = ExtractSpanText(ExtractParentNode("//div[@class='weclever_action_bought_icon']"));
            //pageInfo.Received = ExtractText("//span[@class='weclever_action_important1']", out res);
            //pageInfo.ValidPeriod = ExtractText("//div[@class]/<br>/span[@class='weclever_action_important2']", out res);
            pageInfo.ValidPeriod = ExtractSpanText(ExtractParentNode("//div[@class='weclever_action_finish_icon']"));
            pageInfo.Deadline = ExtractSpanText(ExtractParentNode("//div[@class='weclever_action_time_icon']"));
            pageInfo.Pict = ExtractAttribute("//div[@id='weclever_action_pic']/img", "src", out res);
            //weclever_pic_slider_img_box
            if (pageInfo.Pict.Length > 0)
            {                
                //PageCommunication.DownloadFile(pageInfo.Pict, string.Format("/{0}/{1}/{2}.jpg", SiteUrls.ImgsDirectory, LocationCity.NameEng, PositionName));                
                PageCommunication.DownloadFile(pageInfo.Pict, string.Format("{0}/{1}_{2}{3}", SiteUrls.ImgsDirectory, LocationCity.NameEng, PositionName, Path.GetExtension(SiteUrls.UrlParse(pageInfo.Pict).Last())));
            }
            HtmlNodeCollection picNodes = node.SelectNodes("//div[@id='weclever_pic_slider_img_box']/img");
            if (picNodes != null)
            {
                foreach (var n in picNodes)
                {
                    string attr = n.GetAttributeValue("src", string.Empty);
                    if (attr == string.Empty) {continue;}
                    pageInfo.GetPic().Add(attr);
                    PageCommunication.DownloadFile(attr, string.Format("{0}/{1}_{2}_{3}{4}", SiteUrls.ImgsDirectory, LocationCity.NameEng, PositionName, pageInfo.GetPic().Count, Path.GetExtension(attr)));
                }
            }
            //
            pageInfo.Phone = string.Empty;
            pageInfo.Address = string.Empty;
            HtmlNodeCollection nodeCol = node.SelectNodes("//div[@class='weclever_contact']");
            foreach (var n in nodeCol)
            {
                if (null != n.SelectSingleNode(".//div[@class='weclever_cont_address_icon']"))
                {
                    // this is address div
                    HtmlNode tempNode = n.SelectSingleNode(".//div[@class='weclever_cont_textside']");
                    if (tempNode != null)
                    {
                        pageInfo.Address += tempNode.InnerText;
                    }
                }
                if (null != n.SelectSingleNode(".//div[@class='weclever_cont_tel_icon']"))
                {
                    //this is phone div
                    HtmlNode tempNode = n.SelectSingleNode(".//div[@class='weclever_cont_textside']");
                    if (tempNode != null)
                    {
                        pageInfo.Phone += tempNode.InnerText;
                    }
                }
                if (null != n.SelectSingleNode(".//div[@class='weclever_cont_metro_icon']"))
                {
                    //this is phone div
                    HtmlNode tempNode = n.SelectSingleNode(".//div[@class='weclever_cont_textside']");
                    if (tempNode != null)
                    {
                        pageInfo.Metro += tempNode.InnerText;
                    }
                }
            }            

            //
            pageInfo.ShortText = ExtractText("//div[@class='weclever_desgrey']", out res);
            pageInfo.Text = ExtractText("//div[@class='weclever_description']", out res);
            //Regex rx = new Regex("lat:\"[0-9]+(\\.)[0-9]+\",lon:\"[0-9]+\\.[0-9]+\"", RegexOptions.IgnoreCase);
            //Match mc = rx.Match(siteHtml);
            pageInfo.GPS = MatchRegEx("lat:\"[0-9]+(\\.)[0-9]+\",lon:\"[0-9]+\\.[0-9]+\"");
            pageInfo.CityLat = MatchRegEx("cityLat(\\s*)=(\\s*)[0-9]+(\\.)[0-9]+;");
            pageInfo.CityLon = MatchRegEx("cityLon(\\s*)=(\\s*)[0-9]+(\\.)[0-9]+;");




            //cityLat = 55.72;
            //cityLon = 37.6;
            return pageInfo;
        }

        private string MatchRegEx(string pattern)
        {
            Regex rx = new Regex(pattern);
            Match mc = rx.Match(siteHtml);
            return mc.ToString();
        }

        /// <summary>
        /// Extract node by xPath
        /// </summary>
        /// <param name="xPath"></param>
        /// <returns></returns>
        private HtmlNode ExtractNode(string xPath)
        {
            return ExtractNode(node, xPath);
        }

        private HtmlNode ExtractNode(HtmlNode baseNode, string xPath)
        {
            HtmlNode curNode;
            try
            {
                curNode = baseNode.SelectSingleNode(xPath);
            }
            catch
            {
                curNode = null;
            }
            return curNode;
        }

        /// <summary>
        /// find node where innerText contains searchText
        /// </summary>
        /// <param name="xPath"></param>
        /// <param name="innerText"></param>
        /// <returns></returns>
        private HtmlNode NodeWithInnerText(string xPath, string searchText)
        {
            HtmlNodeCollection nodecol = node.SelectNodes(xPath);
            if (nodecol == null) return null;
            foreach (var n in nodecol )
            {
                if (n.InnerText.Contains(searchText)) return n;
            }
            return null;
        }

        private HtmlNode ExtractParentNode(string xPath)
        {
            HtmlNode n = ExtractNode(xPath);
            if (n == null) return null;
            return n.ParentNode;
        }

        private string ExtractSpanText(HtmlNode n)
        {
            if (n == null) return string.Empty;
           
            HtmlNode nod = n.SelectSingleNode(".//span[@class]");
            if (nod == null) return string.Empty;
            return nod.InnerText;
        }

        private string ExtractAttribute(string xPath, string attrName, out bool res)
        {
            HtmlNode curNode = ExtractNode(xPath);
            if (curNode == null)
            {
                res = false;
                return string.Empty;
            }
            res = true;
            return curNode.GetAttributeValue(attrName, String.Empty);
        }

        private string ExtractText(string xPath, out bool res)
        {
            HtmlNode curNode = ExtractNode(xPath); 
            if (curNode == null)
            {
                res = false;
                return string.Empty;
            }
            res = true;
            return curNode.InnerText;        
        }

    }
}
/*
  <script>var inputData = [ 
        
            {
            title:"Скидка 81% на 3 часа игры в боулинг в боулинг-центре «Корабль»!",
            discount:"81",
            sold:"45",
            cost:"450",
            left:"26",
            action_id:"7365",
            alias:"/korabl",
            address:"ул. Керченская, д. 1б",
            lat:"55.654806",lon:"37.583393"
            }

                                    ];
        cityLat=55.72;
        cityLon=37.6;
*/
//http://maps.google.com/maps/api/staticmap?center=55.72,37.6&zoom=12&size=400x400&maptype=roadmap&sensor=true&markers=color:blue%7Clabel:S%7C55.654806,37.583393